package com.wowangz.cms.systemmanage.te.service;

import java.io.IOException;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import com.google.common.collect.ImmutableMap;
import com.iol.common.sender.MailSender;
import com.wowangz.cms.syscore.utils.PropertyPlaceholderConfigurerExt;
import com.wowangz.cms.systemmanage.te.dao.FeedbackMapper;
import com.wowangz.cms.systemmanage.te.pojo.Feedback;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

@Service
@EnableScheduling
public class AutoSendFeedbackEmailService {

	@Autowired
	private MailSender mailSender;

	@Autowired
	private FeedbackMapper feedbackMapper;

	@Autowired
	private Configuration freemarkerConfiguration;

	/**
	 * 每周一凌晨6点定时发送意见反馈邮件
	 */
	@Scheduled(cron = "0 0 6 ? * MON")
	public void sendEmail() {
		String ymd = new DateTime().minusDays(7).toString("yyyy-MM-dd");
		List<Feedback> list = feedbackMapper.listFeedbackByYMD(ymd);
		if (null != list && list.size() > 0) {
			// 发送邮件
			try {
				String title = ymd + "至" + new DateTime().toString("yyyy-MM-dd") + "意见反馈内容";
				ImmutableMap<String, Object> context = new ImmutableMap.Builder<String, Object>().put("title", title).put("feedbacks", list).build();
				Template emailTemplate = freemarkerConfiguration.getTemplate("feedback_email.ftl", "utf-8");
				String emailHtml = FreeMarkerTemplateUtils.processTemplateIntoString(emailTemplate, context);
				mailSender.setFromName("小尾巴官方邮箱");
				String emailsStr = (String) PropertyPlaceholderConfigurerExt.getContextProperty("send.email.list");
				if (StringUtils.isNotBlank(emailsStr)) {
					String[] arr = emailsStr.split(",");
					if (null != arr && arr.length > 0) {
						for (String email : arr) {
							mailSender.send(email, title, emailHtml);
						}
					}
				}
			} catch (TemplateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}
}
